<template>
    <!-- 增加操作 -->
    <el-button v-if="tempData.length <= 0" :icon="Plus" type="warning" size="small" @click="addOne"></el-button>
    <el-table v-loading='loading' :data="tempData" stripe fit v-if="tempData.length != 0">
        <el-table-column label="number" prop="number" type="index" :index="indexMethod" width="80px"
            align="center"></el-table-column>
        <el-table-column label="host" prop="host" width="300px"></el-table-column>
        <el-table-column label="description" prop="description" width="300px"></el-table-column>
        <el-table-column label="path" prop="path" width="300px"></el-table-column>
        <el-table-column label="method" prop="method" width="100%" align="center"></el-table-column>
        <el-table-column label="code" prop="code" width="100%" align="center"></el-table-column>
        <el-table-column label="json_body" prop="json_body" width="100%" align="center"></el-table-column>
        <el-table-column label="params" prop="params" show-overflow-tooltip='true'>
            <template #default="scope">
                <div>{{ JSON.stringify(scope.row.params, null, 1) }}</div>
            </template>
        </el-table-column>
        <el-table-column label="data" prop="data" show-overflow-tooltip='true'>
            <template #default="scope">
                <div>{{ JSON.stringify(scope.row.data, null, 1) }}</div>
            </template>
        </el-table-column>
        <el-table-column label="headers" prop="headers" show-overflow-tooltip='true'>
            <template #default="scope">
                <div>{{ JSON.stringify(scope.row.headers, null, 1) }}</div>
            </template>
        </el-table-column>
        <el-table-column label="response" prop="response" show-overflow-tooltip='true'>
            <template #default="scope">
                <div>{{ JSON.stringify(scope.row.response, null, 1) }}</div>
            </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center" fixed="right">
            <template #default="scope">
                <!-- 编辑操作 -->
                <el-button :icon="Edit" type="primary" size="small" v-if="!scope.row.edit && !scope.row.EditDisabled"
                    :disabled="scope.row.EditDisabled" @click="editTemp(scope)"></el-button>
                <el-button :icon="Check" type="success" size="small" v-if="scope.row.edit" :loading="scope.row.checkLoading"
                    @click="editTemp(scope, 'edit')"></el-button>
                <el-button :icon="Close" type="success" size="small" v-if="scope.row.EditDisabled"
                    @click="myClose(scope)"></el-button>
                <!-- 增加操作 -->
                <el-button :icon="Plus" type="warning" size="small" @click="addTemp(scope)"></el-button>
                <!-- 删除操作 -->
                <el-button :icon="Delete" type="danger" size="small" v-if="!scope.row.del && !scope.row.delDisabled"
                    :disabled="scope.row.delDisabled" @click="delTemp(scope)"></el-button>
                <el-button :icon="Check" type="success" size="small" v-if="scope.row.del" :loading="scope.row.delLoading"
                    @click="delTemp(scope, 'del')"></el-button>
                <el-button :icon="Close" type="success" size="small" v-if="scope.row.delDisabled"
                    @click="myClose(scope)"></el-button>

            </template>
        </el-table-column>
    </el-table>
    <!-- 新增修改数据的弹窗 -->
    <el-dialog v-model='tempDialog' width="60%" :title="tempTitle" :close-on-click-modal=false :close-on-press-escape=false
        @close="closeTempDialog(tempInfo)" draggable v-if="tempDialog">
        <el-button type="success" @click="curlDialog = true">解析CURL</el-button>
        <br>
        <br>
        <el-form v-model="tempInfo" label-width="75px">
            <el-form-item label="Host" prop="host" :required="true">
                <el-input v-model="tempInfo.host"></el-input>
            </el-form-item>
            <el-form-item label="Path" prop="path" :required="true">
                <el-input v-model="tempInfo.path"></el-input>
            </el-form-item>
            <el-form-item label="Method" :required="true">
                <el-select v-model="tempInfo.method" placeholder="Method" style="width: 115px">
                    <el-option label="GET" value="GET" />
                    <el-option label="POST" value="POST" />
                    <el-option label="PUT" value="PUT" />
                    <el-option label="DELETE" value="DELETE" />
                    <el-option label="HEAD" value="HEAD" />
                    <el-option label="OPTIONS" value="OPTIONS" />
                    <el-option label="PATCH" value="PATCH" />
                </el-select>
            </el-form-item>
            <el-form-item label="Code" :required="true">
                <el-input v-model="tempInfo.code" style="width: 115px"></el-input>
            </el-form-item>
            <el-form-item label="Description" prop="description" >
                <el-input v-model="tempInfo.description"></el-input>
            </el-form-item>
            <el-button type="info" @click="initData()">初始化</el-button>
            <el-button type="success" @click="formatData()">格式化</el-button>
            <el-button type="warning" @click="emptyData()">清空数据</el-button>
            <el-button type="primary" @click="confirmData()">确定</el-button>
            <el-tabs v-model="activeName">
                <el-tab-pane label="Params" name="Params">
                    <el-input type="textarea" v-model="params" :rows="paramsLen" spellcheck="false"></el-input>
                </el-tab-pane>
                <el-tab-pane label="Data" name="Data">
                    <el-input type="textarea" v-model="data" :rows="dataLen" spellcheck="false"></el-input>
                </el-tab-pane>
                <el-tab-pane label="Headers" name="Headers">
                    <el-input type="textarea" v-model="headers" :rows="headersLen" spellcheck="false"></el-input>
                </el-tab-pane>
                <el-tab-pane label="Response" name="Response">
                    <el-input type="textarea" v-model="response" :rows="responseLen" spellcheck="false"></el-input>
                </el-tab-pane>
            </el-tabs>
        </el-form>
    </el-dialog>
    <!-- 解析CURL弹窗 -->
    <el-dialog v-model='curlDialog' width="50%" title="解析CURL" draggable v-if="curlDialog">
        <el-input type="textarea" v-model="curlData" rows="10" spellcheck="false"></el-input>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="curlDialog = false">取消</el-button>
                <el-button type="primary" @click="curlHeader()">确认</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script>
import { ElMessage, ElNotification } from 'element-plus'
import { Edit, Check, Plus, Delete, Close } from '@element-plus/icons-vue'
import _ from 'lodash'
export default {
    name: 'TempData',
    props: {
        'tempData': Array,
        'tempId': Number
    },

    data() {
        return {
            Edit,
            Check,
            Plus,
            Delete,
            Close,
            tempDialog: false,
            tempTitle: '',
            tempInfo: {},
            tempRow: {},
            tempInit: {
                temp_id: this.tempId,
                number: 0,
                host: '',
                path: '',
                method: 'GET',
                code: 200,
                json_body: 'body',
                params: {},
                data: {},
                headers: {},
                response: {},
                edit: false,
                EditDisabled: false,
                del: false,
                delDisabled: false,
                add: true
            },

            // json
            activeName: 'Params',
            params: {},
            data: {},
            headers: {},
            response: {},
            paramsLen: 0,
            dataLen: 0,
            headersLen: 0,
            responseLen: 0,

            curlDialog: false,
            curlData: ''
        }
    },



    methods: {
        addOne() {
            this.tempData.push(_.cloneDeep(this.tempInit))
        },
        // 解析curl
        curlHeader() {
            var curlList = this.curlData.split("\\")

            for (var x in curlList) {
                var newStr = curlList[x].trim()
                if (x == 0) {
                    console.log(newStr.match(/\'(.*?)\'/g));
                } else {
                    console.log(newStr.match(/\-(.*?)\'/g));
                }
                // console.log(newStr);
            }
        },
        // 新增数据接口
        addTemp(scope) {
            var tempInfo = {
                temp_id: scope.row.temp_id,
                number: scope.$index + 1,
                host: '',
                path: '',
                method: 'GET',
                code: 200,
                json_body: 'body',
                params: {},
                data: {},
                headers: {},
                response: {},
                description: '',
                edit: false,
                EditDisabled: false,
                del: false,
                delDisabled: false,
                add: true
            }
            this.tempData.splice(scope.$index + 1, 0, tempInfo)
        },
        // 修改数据接口
        async editTemp(scope, type) {
            scope.row.index = scope.$index
            this.tempRow = scope.row
            this.tempInfo = _.cloneDeep(scope.row)

            this.params = JSON.stringify(this.tempInfo.params, null, 8)
            this.data = JSON.stringify(this.tempInfo.data, null, 8)
            this.headers = JSON.stringify(this.tempInfo.headers, null, 8)
            this.response = JSON.stringify(this.tempInfo.response, null, 8)
            this.paramsLen = 15
            this.dataLen = 15
            this.headersLen = 15
            this.responseLen = 15


            this.tempTitle = '对模板接口数据查看或编辑'
            if (type == 'edit') {
                scope.row.checkLoading = true
                var tempInfo = {
                    temp_id: this.tempId,
                    number: this.tempInfo.number,
                    host: this.tempInfo.host,
                    path: this.tempInfo.path,
                    code: this.tempInfo.code,
                    method: this.tempInfo.method,
                    params: this.tempInfo.params,
                    json_body: this.tempInfo.json_body,
                    data: this.tempInfo.data,
                    file: false,
                    file_data: [],
                    headers: this.tempInfo.headers,
                    response: this.tempInfo.response,
                    description: this.tempInfo.description
                }
                if (this.tempInfo.add) {
                    await this.$http({
                        url: '/template/add/api',
                        method: 'PUT',
                        data: JSON.stringify(tempInfo),
                        headers: {
                            'content-type': "application/json"
                        }
                    }).then(
                        function () {
                            ElNotification.success({
                                title: 'Success',
                                message: '新增成功',
                                offset: 200,
                            })
                        }
                    ).catch(
                        function (error) {
                            ElMessage.error(error.message)
                        }
                    )
                    // 刷新列表
                    this.getTempData()

                } else {
                    await this.$http({
                        url: '/template/edit/api',
                        method: 'PUT',
                        data: JSON.stringify(tempInfo),
                        headers: {
                            'content-type': "application/json"
                        }
                    }).then(
                        function () {
                            ElNotification.success({
                                title: 'Success',
                                message: '修改成功',
                                offset: 200,
                            })
                        }
                    ).catch(
                        function (error) {
                            ElMessage.error(error.message)
                        }
                    )
                }

                scope.row.edit = false
                scope.row.delDisabled = false
                scope.row.checkLoading = false
            } else {
                this.tempDialog = true
            }
        },
        // 确认数据
        confirmData() {
            try {
                this.tempInfo.params = JSON.parse(this.params)
                this.tempInfo.data = JSON.parse(this.data)
                this.tempInfo.headers = JSON.parse(this.headers)
                this.tempInfo.response = JSON.parse(this.response)
            } catch {
                ElMessage.error('Json数据格式有误')
                return
            }

            this.tempDialog = false
            if (this.tempInfo.host && this.tempInfo.path) {
                this.tempInfo.edit = true
                this.tempInfo.delDisabled = true
                if (this.tempInfo.data) {
                    this.tempInfo.json_body = 'data'
                }
                if (this.tempInfo.params) {
                    this.tempInfo.json_body = 'body'
                }
                this.tempData.splice(this.tempInfo.index, 1, this.tempInfo)
            }
        },
        // 删除数据接口
        async delTemp(scope, type) {
            if (type == 'del') {
                scope.row.delLoading = true
                await this.$http({
                    url: '/template/del/api',
                    method: 'DELETE',
                    params: {
                        temp_id: this.tempId,
                        number: scope.row.number
                    }
                }).then(
                    function () {
                        ElNotification.success({
                            title: 'Success',
                            message: '删除成功',
                            offset: 200,
                        })
                    }
                ).catch(
                    function (error) {
                        ElMessage.error(error.message)
                    }
                )
                scope.row.delLoading = false
                // 刷新列表
                this.getTempData()
                scope.row.del = false
                scope.row.EditDisabled = false
            } else {
                if (scope.row.host == '' && scope.row.path == '') {
                    for (var x in this.tempData) {
                        if (x == scope.$index) {
                            this.tempData.splice(x, 1)
                            break
                        }
                    }
                }
                scope.row.del = true
                scope.row.EditDisabled = true
            }
        },
        // 更新列表
        async getTempData() {
            console.log('刷新列表');
            this.tempData.splice(0, this.tempData.length);
            var temp_ = []
            await this.$http.get('/template/data/list?temp_id=' + this.tempId).then(
                function (response) {
                    temp_ = response.data
                    for (var x in temp_) {
                        temp_[x].edit = false
                        temp_[x].EditDisabled = false
                        temp_[x].del = false
                        temp_[x].delDisabled = false
                    }
                }
            ).catch(function (error) {
                ElMessage.error(error.message)
            })
            for (var x in temp_) {
                this.tempData.push(temp_[x])
            }
        },
        // 初始化数据
        initData() {
            try {
                if (this.activeName == 'Params') {
                    this.params = JSON.stringify(this.tempInfo.params, null, 8);
                } else if (this.activeName == 'Data') {
                    this.data = JSON.stringify(this.tempInfo.data, null, 8);
                } else if (this.activeName == 'Headers') {
                    this.headers = JSON.stringify(this.tempInfo.headers, null, 8);
                } else if (this.activeName == 'Response') {
                    this.response = JSON.stringify(this.tempInfo.response, null, 8);
                }
                ElMessage.success('数据初始化成功')
            } catch (e) {
                ElMessage.error('数据初始化失败，格式有误')
            }
        },
        // 格式化数据
        formatData() {
            try {
                if (this.activeName == 'Params') {
                    this.params = JSON.stringify(JSON.parse(this.params), null, 8);
                } else if (this.activeName == 'Data') {
                    this.data = JSON.stringify(JSON.parse(this.data), null, 8);
                } else if (this.activeName == 'Headers') {
                    this.headers = JSON.stringify(JSON.parse(this.headers), null, 8);
                } else if (this.activeName == 'Response') {
                    this.response = JSON.stringify(JSON.parse(this.response), null, 8);
                }
                ElMessage.success('数据格式化成功')
            } catch (e) {
                ElMessage.error('数据格式化失败，格式有误')
            }
        },
        // 清空数据
        emptyData() {
            this.dataInfo = JSON.stringify({}, null, 8);
            if (this.activeName == 'Params') {
                this.params = JSON.stringify({}, null, 8);
            } else if (this.activeName == 'Data') {
                this.data = JSON.stringify({}, null, 8);
            } else if (this.activeName == 'Headers') {
                this.headers = JSON.stringify({}, null, 8);
            } else if (this.activeName == 'Response') {
                this.response = JSON.stringify({}, null, 8);
            }
        },
        // 关闭窗口
        closeTempDialog(row) {
            row.del = false
            row.EditDisabled = false
        },
        // 取消操作
        myClose(scope) {
            if (scope.row.edit && scope.row.add) {
                this.tempData.splice(scope.$index, 1)
            }
            scope.row.edit = false
            scope.row.delDisabled = false
            scope.row.del = false
            scope.row.EditDisabled = false
        },
        indexMethod(index) {
            return this.tempData[index]['number']
        }
    }
}

</script>